package com.ebrothers.isns.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.ebrothers.isns.common.Utils;
import com.ebrothers.isns.vo.Location;

public class LocationDAO extends GenericDAO {

	public long insertLocation(Location loc) throws DAOException {
		long locId = getLocationId(loc);
		if (locId == -1) {
			String sql = "insert into locations (name,longitude,latitude) values ('"
					+ loc.getName()
					+ "',"
					+ loc.getLongitude()
					+ ","
					+ loc.getLatitude() + ");";
			insert(sql);
			locId = getLocationId(loc);
		}
		return locId;
	}

	public long getLocationId(Location loc) throws DAOException {
		String sql = "select id from locations where longitude="
				+ loc.getLongitude() + " and latitude=" + loc.getLatitude();
		ResultSet rs = query(sql);
		try {
			if (rs.next()) {
				return rs.getLong(1);
			}
		} catch (SQLException e) {
			throw new DAOException(e);
		} finally {
			closeResultSet(rs);
		}
		return -1;
	}

	public Location getLocation(long id) throws DAOException {
		String sql = "select * from locations where id=" + id;
		ResultSet rs = query(sql);
		Location location = null;
		try {
			if (rs.next()) {
				location = new Location();
				location.setId(rs.getLong("id"));
				location.setLongitude(rs.getString("longitude"));
				location.setLatitude(rs.getString("latitude"));
				location.setName(Utils.encodeText(rs.getString("name")));
			}
		} catch (SQLException e) {
			throw new DAOException(e);
		} finally {
			closeResultSet(rs);
		}
		return location;
	}
}
